package com.ly.gen.web;

import com.ly.gen.model.ConnInfo;
import com.ly.gen.model.TableInfo;
import com.ly.gen.service.ConnsService;
import com.ly.gen.service.TableContext;
import com.ly.gen.service.TableService;
import com.ly.gen.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/conn")
public class ConnsController {

    @Autowired
    private ConnsService connsService;
    @Autowired
    private TableContext tableContext;

    /**
     * query conn data
     *
     * @author yuan.lei
     * @date 2023/2/7
     **/
    @GetMapping("/list")
    public R queryConnList(@RequestParam Map<String, Object> params) {
        List<ConnInfo> data = connsService.queryList(params);
        return R.ok().put("data", data);
    }

    /**
     * 保存连接信息
     *
     * @author yuan.lei
     * @date 2023/2/7
     **/
    @PostMapping("/save")
    public R saveConn(@RequestBody ConnInfo connInfo) {
        if (connInfo.getId() == null) {
            connsService.saveConn(connInfo);
        } else {
            connsService.updateConn(connInfo);
        }

        return R.ok();
    }

    /**
     * 获取表
     *
     * @author leiyuan
     * @date 2023/2/19 0019
     **/
    @GetMapping("/get-tables")
    public R getTables(@RequestParam Integer connId, @RequestParam(required = false) String tableName) {
        String dbType = connsService.getDbType(connId);
        TableService service = tableContext.getService(dbType);
        List<TableInfo> dataList = service.getTableNames(connId, tableName);
        return R.ok().put("data", dataList);
    }

    @DeleteMapping("/del/{id}")
    public R delConn(@PathVariable("id") Integer id) {
        connsService.delConn(id);
        return R.ok();
    }
}
